package org.fu.crowd.controller;

import org.fu.crowd.utils.Common;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
public class RedisController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;



    /**
     * 在redis中保存数据
     * @param key
     * @param value
     * @return
     */
    @RequestMapping("/set/RedisKeyValue/Remote")
    Common<String> setRedisKeyValue(@RequestParam("key")String key,
                                    @RequestParam("value")String value){
        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(key,value);
            return Common.successWithoutData();
        }catch (Exception e){
            return Common.failed(e.getMessage());
        }
    }



    /**
     * 在redis中保存数据,有过期时间
     * @param key
     * @param value
     * @return
     */
    @RequestMapping("/set/RedisKeyValue/RemoteWithTimeOut")
    Common<String> setRedisKeyValueRemoteWithTimeOut(
            @RequestParam("key")String key,
            @RequestParam("value")String value,
            @RequestParam("time")Long time,
            @RequestParam("timeUnix") TimeUnit timeUnit){

        try {
            ValueOperations<String, String> operations = stringRedisTemplate
.opsForValue();
            operations.set(key,value,time,timeUnit);
            return Common.successWithoutData();
        }catch (Exception e){
            return Common.failed(e.getMessage());
        }

    }


    /**
     * 根据key 获取value
     * @param key
     * @return
     */
    @RequestMapping("/get/RedisValue/ByKey")
    Common<String> getRedisValueByKey( @RequestParam("key")String key){

        try {
            ValueOperations<String, String> operations = stringRedisTemplate
.opsForValue();
            String s = operations.get(key);
            return Common.successWithoutData(s);
        }catch (Exception e){
            return Common.failed(e.getMessage());
        }

    }


    /**
     *      根据key 删除value
     * @param key
     * @return
     */
    @RequestMapping("/removeRedisValue/ByKeyRemote")
    Common<String> removeRedisValueByKey( @RequestParam("key")String key){
        try {
            stringRedisTemplate
.delete(key);
            return Common.successWithoutData();
        }catch (Exception e){
            return Common.failed(e.getMessage());
        }
    }
}
